import axios from 'axios'
import { baseURL } from '@/config'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

class HttpServer {
  constructor(url = baseURL) {
    this.url = url
    this.queue = []
  }
  getInsideConfig() {
    const config = {
      baseUrl: this.url,
      withCredentials: true,
      timeout:5000
    }
    return config
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options)
    return instance(options)
  }
  interceptors(instance, options) {
    instance.interceptors.request.use(req => {
      NProgress.start()
      if(options.contentType) {
        req.headers['Content-Type'] = options.contentType
      }else {
        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      }
      if(options.headers) {
        for(let key in options.headers) {
          let str = ''
          if(typeof options.headers[key] === 'object') {
            for (let k in options.headers[key]) {
              str += k + '=' + options.headers[key][k] + ';'
            }
            str = str.replace(/\,$/, '')
          }
          req.headers[key] = str
        }
      }
      if(!Object.keys(this.queue).length) {
        //show 遮罩层
      }
      this.queue[options.url] = true
      return req
    }, err => {
      return Promise.reject(err)
    })
    instance.interceptors.response.use(res => {
      delete this.queue[options.url]
      if(this.queue.length === 0) {
        NProgress.done()
      }
      if(res.headers['set-cookie']) {
        document.cookie = res.headers['set-cookie']
      }
      return res
    }, err => {
      if(err.response?.data?.name === 'UNAUTHORIZED') {
        window.sessionStorage.setItem('token', '')
      }
      delete this.queue[options.url]
      return Promise.reject(err)
    })
  }
}

export default HttpServer
